#!/usr/bin/env python3
#coding:utf-8

__author__ = 'xmxoxo<xmxoxo@qq.com>'

import pika
import sys
import time
import random
import numpy as np
from config import *

print(rabbit_user, rabbit_pwd)
print(rabbit_ip,rabbit_port)

#credentials = pika.PlainCredentials('ywt', 'ywt')
#parm = pika.ConnectionParameters(host='127.0.0.1', port=5672, virtual_host='/', credentials=credentials)
credentials = pika.PlainCredentials(rabbit_user, rabbit_pwd)
parm = pika.ConnectionParameters(host=rabbit_ip, port=rabbit_port, virtual_host='/', credentials=credentials)

connection = pika.BlockingConnection(parm)

channel = connection.channel()
channel.exchange_declare(exchange='topic_exchange', exchange_type='topic', durable=True)

# 定义队列
queue_name = str(int(time.time()))
channel.queue_declare(queue=queue_name, durable=True, auto_delete=True)

#result = channel.queue_declare(queue='fj.xm.362', exclusive=True)
#queue_name = result.method.queue
 
binding_keys = sys.argv[1:]
if not binding_keys:
    binding_keys = ["#"]
    #sys.stderr.write("Usage: %s [binding_key]...\n" % sys.argv[0])
    #sys.exit(1)
else:
    print(binding_keys)
    #binding_keys = binding_keys.split(' ')
 
print('binding_keys:',binding_keys)
for binding_key in binding_keys:
    channel.queue_bind(exchange='topic_exchange',queue=queue_name, routing_key=binding_key)
 
print(' [*] Waiting for logs. To exit press CTRL+C')

v_sum = 0
pool_size = 100
datlst = []
v_ave = 0

def callback(ch, method, properties, body):
    print(" [x] %r:%s" % (method.routing_key, body))
    v = float(body)
    datlst.append(v)
    if len(datlst)>pool_size:
        datlst.pop(0)
    v_sum = sum(datlst)
    v_mean = np.mean(datlst)
    print('total: %f, mean:%f' %(v_sum,v_mean))


#channel.basic_consume(callback, queue=queue_name, no_ack=True)
#channel.start_consuming()

channel.basic_qos(prefetch_count=1)
channel.basic_consume(on_message_callback=callback, queue=queue_name)
channel.start_consuming()

if __name__ == '__main__':
    pass

